package com.zh.freechat.web;

import com.zh.freechat.assemble.ChatMsgWrapper;
import com.zh.freechat.assemble.ChatRelationWrapper;
import com.zh.freechat.assemble.GroupRelationWrapper;
import com.zh.freechat.common.req.EditGroupForm;
import com.zh.freechat.common.req.GroupForm;
import com.zh.freechat.common.resp.ChatGroupVO;
import com.zh.freechat.common.resp.ChatMsgVO;
import com.zh.freechat.common.resp.ChatRelationDTO;
import com.zh.freechat.common.resp.ChatRelationVO;
import com.zh.freechat.domain.auth.LoginUser;
import com.zh.freechat.domain.message.entity.ChatGroupPO;
import com.zh.freechat.domain.message.entity.ChatMsgPO;
import com.zh.freechat.domain.user.service.UserChatService;
import com.zh.webcommon.common.viewdata.ApiResult;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

import static com.zh.mycommon.viewdata.ToWrapper.foreach;

/**
 * 聊天群或聊天会话相关API
 */
@AllArgsConstructor
@RestController
@RequestMapping("/chat")
public class ChatController {
    private UserChatService userChatService;


    /**
     * 获取当前用户的聊天列表
     *
     * @return
     */
    @GetMapping("/relation/{userId}")
    public ApiResult<List<ChatRelationVO>> chatters() {
        var userId = getCurrentUserInfo().getUid();
        List<ChatRelationDTO> chatters = userChatService.findChatRelations(userId);

        return ApiResult.success(foreach(chatters, ChatRelationWrapper::convertVO));
    }

    /**
     * 获取聊天者的聊天消息流
     */
    @GetMapping("/messages/current")
    public ApiResult<List<ChatMsgVO>> messages(@RequestParam("chatId") String chatId
            , @RequestParam("isGroup") Boolean isGroup, @RequestParam(value = "before", defaultValue = "0") long before) {
        //可以去验证一下chatId和userId是不是相关的
        var userId = getCurrentUserInfo().getUid();

        List<ChatMsgPO> messages = userChatService.findChatMsgs(chatId, isGroup, before, 20);
        Collections.reverse(messages); //反转原list
        return ApiResult.success(foreach(messages, ChatMsgWrapper::convertVO));
    }

    /**
     * 创建群组
     */
    @PostMapping("/group/create")
    public ApiResult<String> createGroup(@RequestBody GroupForm form) {
        if (StringUtils.isEmpty(form.getOwnerUid())) {
            var userId = getCurrentUserInfo().getUid();
            form.setOwnerUid(userId);
        }
        var groupNo = userChatService.createGroup(form);
        return ApiResult.success(groupNo);
    }

    /**
     * 解散群组
     */
    @DeleteMapping("/group/delete/{groupNo}")
    public ApiResult<Void> deleteGroup(@PathVariable String groupNo) {
        userChatService.deleteGroup(groupNo);
        return ApiResult.success();
    }

    /**
     * 群组添加成员
     */
    @PutMapping("/group/addMember")
    public ApiResult<Void> groupAddMember(@RequestBody List<GroupForm.MemberItem> items) {
        Assert.notEmpty(items, "items不能为空");
        userChatService.groupAddMembers(items);
        return ApiResult.success();
    }

    /**
     * 群组移除成员
     */
    @DeleteMapping("/group/dropMember")
    public ApiResult<Void> groupDropMember(@RequestBody GroupForm.MemberItem item) {
        userChatService.groupDropMember(item);
        return ApiResult.success();
    }

    /**
     * 修改群名称+头像
     */
    @PutMapping("/group/edit")
    public ApiResult<Void> editGroup(@RequestBody EditGroupForm form) {
        userChatService.editGroup(form, form.getRelId());
        return ApiResult.success();
    }

    /**
     * 根据groupNo，获取群组详情
     */
    @GetMapping("/group/detail/{groupNo}")
    public ApiResult<ChatGroupVO> groupDetail(@PathVariable String groupNo) {
        if (StringUtils.isEmpty(groupNo))
            return ApiResult.fail("groupNo不能为空");

        ChatGroupPO group = userChatService.findGroupByNo(groupNo);
        return ApiResult.success(GroupRelationWrapper.convertVO(group));
    }

    /**
     * 根据Id，获取群组详情
     */
    @GetMapping("/group/{chatId}")
    public ApiResult<ChatGroupVO> groupById(@PathVariable Long chatId) {
        ChatGroupPO group = userChatService.findGroupById(chatId);
        return ApiResult.success(GroupRelationWrapper.convertVO(group));
    }

    /**
     * 获取当前用户的群组列表
     */
    @GetMapping("/group/list")
    public ApiResult<List<ChatGroupVO>> chatGroups() {
        var userId = getCurrentUserInfo().getUid();
        var groupRelList = userChatService.findGroupsByUser(userId);

        return ApiResult.success(foreach(groupRelList, GroupRelationWrapper::convertVO));
    }

    private LoginUser getCurrentUserInfo() {
        return (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

}
